//
//  SandPluginWifi.m
//  sand-plugin-wifi
//
//  Created by Qianjiao Wang on 2021/4/20.
//

#import "SandPluginWifi.h"
#import <SystemConfiguration/CaptiveNetwork.h>

@implementation SandPluginWifi

// 通过宏 UNI_EXPORT_METHOD 将异步方法暴露给 js 端
UNI_EXPORT_METHOD(@selector(getWIFIInfo:callback:))

/// 异步方法（注：异步方法会在主线程（UI线程）执行）
/// @param options js 端调用方法时传递的参数
/// @param callback 回调方法，回传参数给 js 端
- (void)getWIFIInfo:(NSDictionary *)options callback:(UniModuleKeepAliveCallback)callback {
    // options 为 js 端调用此方法时传递的参数
    NSLog(@"%@",options);
    //获取wifi信息逻辑
    NSString *wifiSSID = @"";
    NSString *wifiBSSID = @"";
    NSString *status = @"2500";
    NSString *message = @"获取成功";
    
    CFArrayRef wifiInterfaces = CNCopySupportedInterfaces();
    if (!wifiInterfaces) {
        status = @"2504";
        message = @"获取网络接口失败";
    }else{
        NSArray *interfaces = (__bridge NSArray *)wifiInterfaces;
        for (NSString *interfaceName in interfaces) {
           CFDictionaryRef dictRef = CNCopyCurrentNetworkInfo((__bridge CFStringRef)(interfaceName));
            NSLog(@"sand===%@",dictRef);
           if (dictRef) {
               NSDictionary *networkInfo = (__bridge NSDictionary *)dictRef;
               wifiSSID = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeySSID];
               wifiBSSID = [networkInfo objectForKey:(__bridge NSString *)kCNNetworkInfoKeyBSSID];
               CFRelease(dictRef);
               break;
           }
        }
        CFRelease(wifiInterfaces);
    }
    // 可以在该方法中实现原生能力，然后通过 callback 回调到 js

    // 回调方法，传递参数给 js 端 注：只支持返回 String 或 NSDictionary (map) 类型
    if (callback) {
        //处理bssid少0的问题
        NSArray *array = [wifiBSSID componentsSeparatedByString:@":"];
        if (array.count==6){
            wifiBSSID=[NSString stringWithFormat:@"%@:%@:%@:%@:%@:%@",
                       [self addZero:array[0] withLength:2],
                       [self addZero:array[1] withLength:2],
                       [self addZero:array[2] withLength:2],
                       [self addZero:array[3] withLength:2],
                       [self addZero:array[4] withLength:2],
                       [self addZero:array[5] withLength:2]];
        }
        // 第一个参数为回传给js端的数据，第二个参数为标识，表示该回调方法是否支持多次调用，如果原生端需要多次回调js端则第二个参数传 YES;
        NSLog(@"返回的信息为：%@,%@,%@,%@",status,wifiSSID,wifiBSSID,message);
        callback(@{@"status":status,
                   @"ssid":wifiSSID,
                   @"bssid":wifiBSSID,
                   @"message":message
                 },NO);
    }
}
//字符串补零操作

- (NSString *)addZero:(NSString *)str withLength:(int)length{
    NSString *string = nil;

    if (str.length==length) {
        return str;

    }

    if (str.length<length) {
        NSUInteger inter = length-str.length;

        for (int i=0;i< inter; i++) {
            string = [NSString stringWithFormat:@"0%@",str];

            str = string;

        }

    }

    return string;

}
@end
